import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.apache.log4j.Logger;

public class WaitForTimer2 implements JavaDelegate {
	private static Logger logger = Logger.getLogger("WaitForTimer");

	@Override
	public void execute(DelegateExecution arg0) throws Exception {
		String[] ids = (String[]) arg0.getVariable("ids");
		ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
		HistoryService historyService = processEngine.getHistoryService();
		arg0.setVariable("result", 0);
		try {
			for (String processId : ids) {
				if (!historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult().getEndActivityId()
						.equals("endevent1")) {
					logger.info(arg0.getProcessInstanceId() + " subprocesses not finished ");
					return;
				}
			}
		} catch (Exception e) {
			logger.info("Error in checking subprocesses state ", e);
			logger.info(arg0.getProcessInstanceId() + " subprocesses not finished ");
			return;
		}
		logger.info("All subprocesses finished for " + arg0.getProcessInstanceId());
		arg0.setVariable("result", 1);

	}

}
